<template>
  <div class="page bgc-fff">
    <!-- title -->
    <div class="title-wrap pad-t30 f16 c-333">
      公司注册
    </div>
    <!-- input查询 -->
    <div class='login-input-wrap'>
      <!-- <input type="hidden" name="_csrf" id="order_csrf" value="<?php //echo Yii::$app->request->csrfToken?>"/> -->
      <div class="login-input-box">
        <div class="input-cells a-between">
          <div class="flex l-center a-left">
            <div class="f-fl input-label a-between w90">手机号码</div>
            <input type="tel" class=" cell-input w150" placeholder="请输入手机号码"
              maxlength="11" v-model.trim="registParam.phone" @keyup = "phoneKeyup"/>
          </div>
          <img v-show="registParam.phone" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('phone')">
        </div>
        <div class="input-cells a-between mt10">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">登录密码</div>
            <input type="password" class=" cell-input w150"   placeholder="请输入6-20位密码"
              @blur="checkTwoPsw"  maxlength="18"  v-model.trim="registParam.password"  />
          </div>
          <img v-show="registParam.password" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('password')">
        </div>
        <div class="input-cells a-between mt10">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">确认密码</div>
            <input type="password" class=" cell-input w150"   placeholder="请再次确认密码"
              @blur="checkTwoPsw" style="text-align:left;" maxlength="18"  v-model.trim="registParam.passwords"/>
          </div>
          <img v-show="registParam.passwords" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('passwords')">
        </div>
        <div class="input-cells a-between mt10">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">公司名称</div>
            <input type="text" class=" cell-input w150"   placeholder="请输入公司名称"
              style="text-align:left;"  v-model.trim="registParam.companyName"  />
          </div>
          <img v-show="registParam.companyName" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('companyName')">
        </div>
        <div class="input-cells a-between mt10">
          <div class="flex l-center a-left">
            <div class="f-fl input-label w90">纳税人识别号</div>
            <input type="text" class=" cell-input w150"   placeholder="请输入纳税人识别号"
              style="text-align:left;"   v-model.trim="registParam.taxPayerId"/>
          </div>
          <img v-show="registParam.taxPayerId" class="icon-delete"
              :src="staticImgData.imgurla" alt="" @click="cleanInput('taxPayerId')">
        </div>
      </div>
      <div>
        <p class="large-btn" :disabled="disabled" :class="[{'bgc-7cbdff':!disabled}]" @click="subAxios">{{sub_btn_msg}}</p>
      </div>
      <div class="flex a-right l-center pad15">
        <span class="f12 c-01a4f6" @click="toLoginNormal">已有账号前往登录</span>
      </div>
      <!-- <div class="flex a-center l-center mt50">
        <span class="line-left"></span>
        <span class="c-B2B2B2 f12" style="line-height:.15rem;">绑定手机即可登录接单</span>
        <span class="line-right"></span>
      </div> -->
    </div>

    <v-loading  v-show="loadingShow" style="z-index:11" ></v-loading>
  </div>
</template>

<script>
  import Loading from '@/components/common/loading/loading.vue'
  import { Toast } from 'mint-ui'
  import Utils from '@/utils/util'
  import * as DevopApi from '@/api/devop'
  import * as AccountApi from '@/api/account'
  // import * as ThreeStorage from '@/utils/store/token.js'
  export default {
    name: 'company-signup',
    data() {
      return {
        nums: 15,
        staticImgData: {
          imgurla: require('@/assets/image/common/icon_delete.png')
        },
        registParam: {
          phone: '',
          password: '',
          passwords: '',
          companyName: '',
          taxPayerId: ''
        },
        sub_btn_msg: '注册',
        loadingShow: false, // loading显隐
        disabled: true, // 登录禁止点击
        prevent_repeat: false,
        loadingFail: false
      }
    },
    components: {
      'v-loading': Loading
    },
    created() {
      // this.transformDateStr()
    },
    computed: {
      registParamCom() {
        const { phone, password, passwords, companyName, taxPayerId } = this.registParam
        return {
          phone,
          password,
          passwords,
          companyName,
          taxPayerId
        }
      }
    },
    watch: {
      registParamCom: {
        handler: function(newValData) {
          const that = this
          const vala = newValData.phone.length
          const valb = newValData.password
          const valc = newValData.passwords
          const vald = newValData.password.length
          const vale = newValData.passwords.length
          const valf = newValData.companyName
          const valg = newValData.taxPayerId
          if (vala === 11 && valb !== '' && valc !== '' && valb === valc && vald > 5 && vale > 5 && vald < 20 && vale < 20 && valf !== '' && valg !== '') {
            that.disabled = false
          } else {
            that.disabled = true
          }
          if (vald > 20 && vale > 20) {
            Toast({
              message: '请输入6-20位的密码',
              duration: 1500
            })
          }
        },
        deep: true
      }
    },
    mounted() {

    },
    methods: {
      cleanInput: function(val) {
        const res_val = val
        if (res_val === 'phone') {
          this.registParam.phone = ''
        } else if (res_val === 'password') {
          this.registParam.password = ''
        } else if (res_val === 'passwords') {
          this.registParam.passwords = ''
        } else if (res_val === 'companyName') {
          this.registParam.companyName = ''
        } else if (res_val === 'taxPayerId') {
          this.registParam.taxPayerId = ''
        }
      },
      phoneKeyup: function() { // 电话号码输入框
        const key = this.registParam.phone.length
        if (key === 11) {
          this.code_prevent = false
          this.telFormatting(this.registParam.phone)
        }
      },
      telFormatting: function(param) { // 电话号码格式化
        let num = this.registParam.phone
        let num_ = this.registParam.phone
        num = num.replace(/\s/g, '').substring(0, 3).replace(/(.{3})/g, '$1')
        num_ = num_.replace(/\s/g, '').substring(3).replace(/(.{4})/g, '$1')
        this.registParam.phone = num + num_
        this.registParam.phone = (num + num_).substring(0, 13)
      },
      checkTwoPsw: function() {
        const that = this
        // const vala = this.registParam.phone
        const valb = this.registParam.password
        const valc = this.registParam.passwords
        const vald = this.registParam.password.length
        const vale = this.registParam.passwords.length
        // const valf = this.registParam.companyName
        // const valg = this.registParam.taxPayerId
        if (vald > 5 && vale > 5) {
          if (valb !== valc) {
            Toast({
              message: '二次密码不一致',
              duration: 500
            })
            that.disabled = true
          }
        }
      },
      transformDateStr: function(str) {
        const now_str = str
        let timeStamp_num = ''
        // console.log('indexOf年', now_str.indexOf('年'), 'indexOf月', now_str.indexOf('月'))
        // 2015年6月10日 => 2015-6-10
        if (now_str) {
          if (now_str.indexOf('年') !== -1 && now_str.indexOf('月') !== -1) {
            const str1 = now_str.replace('年', '-')
            const str2 = str1.replace('月', '-')
            const str3 = str2.replace('日', '')
            timeStamp_num = Date.parse(new Date(str3))
          } else if (now_str.indexOf('-') !== -1) {
            // 排除 20151012类型, now_str = 2018-5-6
            timeStamp_num = Date.parse(new Date(now_str))
          } else {
            // 未知其他类型的，辨别不出来的 处理为null
            timeStamp_num = null
          }
          // console.log('now_str', now_str, 'timeStamp_num', timeStamp_num)
          return timeStamp_num
        } else {
          // now_str = null
          timeStamp_num = now_str
          return timeStamp_num
        }
      },
      subAxios: function() {
        // 公共验证
        const that = this
        const mobile = that.registParam.phone.replace(/\s/g, '')
        const password = that.registParam.password.replace(/\s/g, '')
        const companyName = that.registParam.companyName.replace(/\s/g, '')
        const taxPayerId = that.registParam.taxPayerId.replace(/\s/g, '')
        const toParamCompany = {
          creditno: taxPayerId,
          company: companyName
        }
        const check_res = that.checkParam(that.registParam)
        if (check_res) {
          that.loadingShow = true
          // console.log('toParam', toParam)
          if (that.prevent_repeat) { return }
          // that.sub_btn_msg = '注册中…'
          that.prevent_repeat = true
          DevopApi.getCompanyInfo(toParamCompany).then(res => {
            if (res.code === 0) {
              if (res.data) {
                const { approvaldate, name, creditno, enddate, canceldate, legalperson, orgno, province, regaddress,
                  regcapital, regdate, regno, regorgan, scope, startdate, status, type } = res.data
                const approvaldate_num = this.transformDateStr(approvaldate)
                const enddate_num = this.transformDateStr(enddate)
                const canceldate_num = this.transformDateStr(canceldate)
                const regdate_num = this.transformDateStr(regdate)
                const startdate_num = this.transformDateStr(startdate)
                const toParam = {
                  isOpenUp: 1,
                  username: mobile,
                  mobile: mobile,
                  corpName: companyName,
                  taxpayerId: taxPayerId,
                  password: password,
                  name, creditno,
                  approvaldate: approvaldate_num, enddate: enddate_num,
                  canceldate: canceldate_num, regdate: regdate_num,
                  startdate: startdate_num, legalperson, orgno, province, regaddress,
                  regcapital, regno, regorgan, scope, status, type
                }
                // 单点注册
                AccountApi.registerTenant(toParam).then(res => {
                  if (res.data.code === 0) {
                    that.loadingShow = false
                    const loginType = 'driver'
                    this.$store.commit('SET_LOGIN_TYPE', loginType)
                    this.$router.push({ name: 'signup-success', params: { toParam }})
                  } else {
                    that.loadingShow = false
                    Toast({
                      message: res.data.message || '注册用户失败',
                      duration: 1000
                    })
                    return
                  }
                  that.prevent_repeat = false
                }).catch(error => {
                  that.loadingShow = false // 如果注册失败
                  that.prevent_repeat = false
                  Toast({
                    message: error.message || '系统繁忙，请稍候再试',
                    duration: 1000
                  })
                })
              } else {
                that.loadingShow = false // 如果注册失败
                that.prevent_repeat = false
                Toast({
                  message: '企业信息不存在，请联系管理员！',
                  duration: 1000
                })
              }
            }
          }).catch(res => {
            this.loadingShow = false
            that.prevent_repeat = false
            console.warn('error', res)
          })
        }
      },
      checkParam: function(params) {
        const { phone, password, passwords, companyName, taxPayerId } = params
        if (phone === '') {
          Toast({
            message: '请输入手机号码！',
            duration: 1000
          })
          return
        }
        if (password === '') {
          Toast({
            message: '请输入您的密码！',
            duration: 1000
          })
          return
        }
        const password_res = password.length
        if (password_res < 6 || password_res > 20) {
          Toast({
            message: '请输入6-20位密码！',
            duration: 1000
          })
          return
        }
        if (passwords === '') {
          Toast({
            message: '请输入确认密码！',
            duration: 1000
          })
          return
        }
        if (password !== passwords) {
          Toast({
            message: '二次密码不一致！',
            duration: 1000
          })
          return
        }
        const phone_res = Utils.checkMobile(phone)
        if (!phone_res) {
          Toast({
            message: '请输入有效的手机号码！',
            duration: 1000
          })
          return
        }
        if (companyName === '') {
          Toast({
            message: '请输入公司名称！',
            duration: 1000
          })
          return
        }
        if (taxPayerId === '') {
          Toast({
            message: '请输入纳税人识别号！',
            duration: 1000
          })
          return
        }
        let taxPayerId_res
        if (taxPayerId.length === 15) {
          // 旧的纳税识别号15位
          taxPayerId_res = Utils.checkTaxpayerId(taxPayerId)
        } else if (taxPayerId.length === 18) {
          // 三证合一后 18位统一社会信用编码校验
          taxPayerId_res = Utils.CheckSocialCreditCodeOrg(taxPayerId)
        }
        if (!taxPayerId_res) {
          Toast({
            message: '请输入正确的纳税人识别号！',
            duration: 1500
          })
          return
        }
        return true
      },
      toLoginNormal: function() {
        this.$router.push({ name: 'signup-normal' })
      }
    }
  }
</script>

<style scoped>
  @import '../../styles/util.css';
  @import '../../styles/login_regist.css';
  .input-label.w90{
    text-align: center;
    width: .9rem;
  }
  /* input 与删除 */
  .f-fl.input-label{
    margin-right: 0;
  }
  .cell-input.w150{
    width: 1.5rem;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    text-align:left;
  }
  .input-cells.a-between{
    -webkit-justify-content: space-between;
    -moz-justify-content: space-between;
    -ms-justify-content: space-between;
    -webkit-box-pack: justify;
    justify-content: space-between;
  }
  .input-cells>img{
    display: block;
    width: .32rem;
    height: .32rem;
    margin-right: 0;
    padding-right: 0.08rem;
  }
</style>
